package com.zl.cms.util;

import com.google.common.base.Optional;

import java.sql.*;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-1-14 Time: 下午2:03 用于进行单元测试提供数据库链接
 */
public class DbUtil {
  public static Connection getConnection(String url, String username, String password) {
    Connection con = null;
    // sessionVariables=FOREIGN_KEY_CHECKS=0 操作表中数据时忽略外键关联
    try {
      con = DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
    return con;
  }


  public static void close(ResultSet rs, Statement stmt, Connection conn) {
    Optional<ResultSet> rsOpt = Optional.fromNullable(rs);
    Optional<Statement> stmtOpt = Optional.fromNullable(stmt);
    Optional<Connection> connOpt = Optional.fromNullable(conn);

    try {
      if (rsOpt.isPresent()) {
        rsOpt.get().close();
        rsOpt = null;
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (stmtOpt.isPresent()) {
          stmtOpt.get().close();
          stmtOpt = null;
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      } finally {
        try {
          if (connOpt.isPresent()) {
            connOpt.get().close();
            connOpt = null;
          }
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }

  }

  public static void closeConnection(Connection conn) {
    close(null, null, conn);
  }

  public static void closeStatement(Statement statement) {
    close(null, statement, null);
  }

  public static void closeResultSet(ResultSet rs) {
    close(rs, null, null);
  }
}
